﻿using System;
using System.Collections.Generic;
using System.Data;

namespace YJKFamilyLibDataManager
{
	public class MySqlCategoryParamTable : ICategoryParamTable
	{
		public MySqlCategoryParamTable(MySqlDatabase db)
		{
			this.mDatabase = db;
		}

		public void Add(DbCategory category, List<DbParamDefinition> cpdl)
		{
			if (this.mDatabase.Connection.State == ConnectionState.Closed)
			{
				this.mDatabase.Connection.Open();
			}
			for (int i = 0; i < cpdl.Count; i++)
			{
				this.mDatabase.ExecuteCommand(string.Format("insert into CategoryParamTable(ParamName,CategoryGUID,Unit,Description) values('{0}','{1}','{2}','{3}')", new object[]
				{
					cpdl[i].Name,
					category.Guid.ToString(),
					cpdl[i].Unit,
					cpdl[i].Description
				}));
			}
			if (this.mDatabase.Connection.State == ConnectionState.Open)
			{
				this.mDatabase.Connection.Close();
			}
		}

		public List<DbParamDefinition> this[DbCategory category]
		{
			get
			{
				if (this.mDatabase.Connection.State == ConnectionState.Closed)
				{
					this.mDatabase.Connection.Open();
				}
				List<DbParamDefinition> list = new List<DbParamDefinition>();
				DataTable dataTable = this.mDatabase.ExecQuery("select ParamName,Unit,Description from CategoryParamTable where CategoryGUID='" + category.Guid.ToString() + "'");
				if (this.mDatabase.Connection.State == ConnectionState.Open)
				{
					this.mDatabase.Connection.Close();
				}
				if (dataTable != null)
				{
					for (int i = 0; i < dataTable.Rows.Count; i++)
					{
                        list.Add(new DbParamDefinition(dataTable.Rows[i][0].ToString().Trim(), 0, ParamDefinitionType.CaregoryParam, (Autodesk.Revit.DB.BuiltInParameterGroup)(-1))
						{
							Unit = dataTable.Rows[i][1].ToString().Trim(),
							Description = dataTable.Rows[i][2].ToString().Trim()
						});
					}
				}
				return list;
			}
		}

		public void Remove(DbCategory category)
		{
			if (this.mDatabase.Connection.State == ConnectionState.Closed)
			{
				this.mDatabase.Connection.Open();
			}
			this.mDatabase.ExecuteCommand("delete from CategoryParamTable where CategoryGUID='" + category.Guid.ToString() + "'");
			if (this.mDatabase.Connection.State == ConnectionState.Open)
			{
				this.mDatabase.Connection.Close();
			}
		}

		private MySqlDatabase mDatabase;
	}
}
